package com.example.interceptor;

import com.example.context.BaseContext;
import com.example.properties.JwtProperties;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    /**
     * 校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        //2、校验令牌
        try {
            log.info("jwt校验:"+token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            //获取用户id
            Long id = Long.valueOf(claims.get("id").toString());
            log.info("当前用户id："+id);
            //将id放进线程
            BaseContext.setCurrentId(id);
            //通过，放行
            return true;
        } catch (Exception ex) {
            //不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
